<?php

ini_set('display_errors', 1);
error_reporting(E_ALL | E_STRICT);
set_time_limit(60*60);
ini_set('memory_limit', '128M');
date_default_timezone_set('America/New_York');


class PostEdu
{
	private $_dbconn;
	private $_user;
	private $_uid;
	private $_requestUrl;
	private $_errors = array();
	private $_states = array(
							'AL' => 'Alabama',
							'AK' => 'Alaska',
							'AR' => 'Arkansas',
							'AZ' => 'Arizona',
							'CA' => 'California',
							'CO' => 'Colorado',
							'CT' => 'Connecticut',
							'DE' => 'Delaware',
							'DC' => 'District of Columbia',
							'FL' => 'Florida',
							'GA' => 'Georgia',
							'HI' => 'Hawaii',
							'ID' => 'Idaho',
							'IL' => 'Illinois',
							'IA' => 'Iowa',
							'KS' => 'Kansas',
							'KY' => 'Kentucky',
							'LA' => 'Louisiana',
							'ME' => 'Maine',
							'MD' => 'Maryland',
							'MA' => 'Massachusetts',
							'MI' => 'Michigan',
							'MN' => 'Minnesota',
							'MS' => 'Mississippi',
							'MO' => 'Missouri',
							'MT' => 'Montana',
							'NE' => 'Nebraska',
							'NV' => 'Nevada',
							'NH' => 'New Hampshire',
							'NJ' => 'New Jersey',
							'NM' => 'New Mexico',
							'NY' => 'New York',
							'NC' => 'North Carolina',
							'ND' => 'North Dakota',
							'OH' => 'Ohio',
							'OK' => 'Oklahoma',
							'OR' => 'Oregon',
							'PA' => 'Pennsylvania',
							'RI' => 'Rhode Island',
							'SC' => 'South Carolina',
							'SD' => 'South Dakota',
							'TN' => 'Tennessee',
							'TX' => 'Texas',
							'UT' => 'Utah',
							'VA' => 'Virginia',
							'VT' => 'Vermont',
							'WA' => 'Washington',
							'WV' => 'West Virginia',
							'WI' => 'Wisconsin',
							'WY' => 'Wyoming',
						);
	/*
	private $_states = array(
							'Alabama', 'Alaska', 'Arkansas', 'Arizona', 'California', 'Colorado', 'Connecticut', 'DE' => 'Delaware',
							'District of Columbia', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Iowa', 'Kansas', 'Kentucky',
							'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri',
							'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina',
							'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota',
							'Tennessee', 'Texas', 'Utah', 'Virginia', 'Vermont', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming',
						);
	*/
	
	public function __construct() {
		require_once "config.php";
		require_once dirname(__FILE__). '/util/connection.class.php';
		$this->_dbconn = Connection::getInstance();
		$this->_init();
		if (!empty($this->_user))
		{
			$this->buildUrl();
		}
	}
	
	private function _init() {
		$sql = 'select id, firstname, lastname, address1, address2, city, state, zipcode, phone, gender, site_id, birthday from users where optin_edu=1 and phone is not null limit 1';
		try{
			$result = $this->_dbconn->query($sql);
			if (count($result) > 0) {
				$this->_user = $result[0];
				$this->_uid = $result[0]['id'];
			} else {
				$this->_user = null;
			}
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	private function buildUrl() {
		if ($this->_user['zipcode']) {
			if (!preg_match('/^\d{5}/', $this->_user['zipcode'])) {
				$this->_errors[] = 'Invalid Zip ' . $this->_user['zipcode'];
			} else {
				$this->_user['zip'] = $this->_user['zipcode'];
			}
		}
		if ($this->_user['phone']) {
			$this->_user['home_phone'] = str_replace('-', '', $this->_user['phone']);
			if (!preg_match('/^\d{10}/', $this->_user['home_phone'])) {
				$this->_errors[] = 'Invalid Phone Number ' . $this->_user['home_phone'];
			}
		}
		if ($this->_user['state']) {
			if (isset($this->_states[$this->_user['state']])) {
				// do nothing
			} else {
				$this->_errors[] = 'US only';
			}
		}
		$currentYear = date('Y');
		$yearBorn = ($currentYear - 21) . '-' . date('m-d');
		if (strtotime($yearBorn) < strtotime($this->_user['birthday']))
		{
			$this->_errors[] = 'Less than 21 years old';
		}
		$this->_user['time_stamp'] = date('m-d-Y H:i:s');
		$this->_user['fname'] = $this->_user['firstname'];
		$this->_user['lname'] = $this->_user['lastname'];
		//$this->_user['user_ip'] = '192.168.34.22';
		if ($this->_user['site_id'] == 1)
		{
			$this->_user['domain'] = 'www.cashdazzle.com';
		}
		else if ($this->_user['site_id'] == 2)
		{
			$this->_user['domain'] = 'www.lalaloot.com';
		}
		else if ($this->_user['site_id'] == 3)
		{
			$this->_user['domain'] = 'www.mommymoolah.com';
		}
		else
		{
			$this->_errors[] = 'Invalid Site ID';
		}
		$this->_user['CID'] = '859';
		$this->_user['SID'] = $this->_user['site_id'];
		unset($this->_user['firstname'], $this->_user['lastname'], $this->_user['id'], $this->_user['zipcode'], $this->_user['phone'], $this->_user['site_id']);
		$this->_requestUrl = 'http://lead5.net/lead_fusion/postLead.fsn?' . http_build_query($this->_user);
		
	}
	
	public function execute() {
		if (empty($this->_requestUrl))
		{
			echo "Empty URL\n";
			exit;
		}
		if (count($this->_errors) == 0) {
			echo $this->_requestUrl . "\n";
			$ch = curl_init($this->_requestUrl);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
			curl_setopt($ch, CURLOPT_HEADER, false);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			$response = curl_exec($ch);
			curl_close($ch);
			$response = $this->resolveResult($response);
			if ($response == 'REJECTED') {
				echo "failed\n";
				$this->fail();
			} elseif ($response == 'SUCCESS') {
				echo "success\n";
				$this->success();
			}
		} else {
			var_dump($this->_user);
			var_dump($this->_errors);
			$this->filtered();
		}
	}
	
	private function success() {
		$sql = 'update users set optin_edu=?, optin_edu_date=? where id=?';
		try{
			return $this->_dbconn->execute($sql, array(time(), date('Y-m-d H:i:s'), $this->_uid));
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	private function fail() {
		$sql = 'update users set optin_edu=? where id=?';
		try{
			return $this->_dbconn->execute($sql, array(2, $this->_uid));
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	private function filtered() {
		$sql = 'update users set optin_edu=? where id=?';
		try{
			return $this->_dbconn->execute($sql, array(3, $this->_uid));
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	private function resolveResult($result) {
		preg_match('/<body>(.*)<\/body>/is', $result, $matches);
		$match = $matches[1];
		$match = trim($match, " \n<br/>");
		return $match;
		/*
		$doc = new DOMDocument();
		$doc->loadHTML($result);
		*/
	}
	
}

//if (date('N') < 6) {
	$postEdu = new PostEdu();
	$postEdu->execute();
//}